package com.imay.live.activity;

import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.DialogPreference;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.imay.base.helper.ActivityHelper;
import com.imay.capturefilter.utils.ICCons;
import com.imay.capturefilter.utils.ICUtils;
import com.imay.cocos.IMayCocos;
import com.imay.live.activity.authentication.AuthenticationActivity;
import com.imay.live.activity.authentication.UserSignActivity;
import com.imay.live.cache.UserInfoCache;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.EventHelper;
import com.imay.live.helper.FileHelper;
import com.imay.live.helper.PreferenceHelper;
import com.imay.live.manager.APPCacheManager;
import com.imay.live.manager.AccountManager;
import com.imay.live.model.UserInfoModel;
import com.imay.live.proto.MessageId;
import com.imay.live.proto.ProtoResult;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.utils.AppUtil;
import com.imay.live.utils.DialogUtil;
import com.imay.live.utils.TimeUtil;
import com.imay.live.utils.ToastUtil;
import com.imay.live.R;
import com.imay.tbas_api.IMYScheduler;
import com.imay.tbas_api.IMYTBASObject;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

/**
 * create by nick
 * 设置界面
 */
public class SettingActivity extends BaseRequestActivity implements View.OnClickListener, ProtoCallBack {


    private TextView tv_setting_imay_number;
    private Button btn_setting_copy;
    private TextView tv_setting_real_name_authentication;
    private TextView tv_setting_cache;
    private String[] toastTexts;
    int index = -1;
    private IMYTBASObject mSocketNotify;

    public static final void start(Context context) {
        context.startActivity(new Intent(context, SettingActivity.class));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_setting;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setTitle(getString(R.string.setting));
        bindViews();
        addListener();
        toastTexts = getResources().getStringArray(R.array.CacheClearToast);


    }


    private void bindViews() {

        tv_setting_imay_number = (TextView) findViewById(R.id.tv_account_phone);
        btn_setting_copy = (Button) findViewById(R.id.btn_setting_copy);
        tv_setting_real_name_authentication = (TextView) findViewById(R.id.tv_setting_real_name_authentication);
        tv_setting_cache = (TextView) findViewById(R.id.tv_setting_cache);
        TextView tv_setting_balance_way = (TextView) findViewById(R.id.tv_setting_balance_way);

        btn_setting_copy.setOnClickListener(this);

        UserInfoModel model = UserInfoCache.getUserInfo();
        if (model != null) {
            tv_setting_imay_number.setText(model.getUser().getRoomId() + "");
            if (model.getRealNameStatus() == 3) {
                tv_setting_real_name_authentication.setText(getResources().getString(R.string.vsign_applysuccess));
                tv_setting_real_name_authentication.setTextColor(getResources().getColor(R.color.text_75));
            } else {
                tv_setting_real_name_authentication.setText(getResources().getString(R.string.not_authentication));
            }
            tv_setting_balance_way.setVisibility(View.GONE);
//            if (model.getLargeVipStatus() == 3) {
//                tv_setting_balance_way.setText("");
//            }else if(model.getLargeVipStatus() == 1){
//                tv_setting_balance_way.setText("审核中");
//            }
            setCacheSizeText();
        }

    }


    private void addListener() {
        $(R.id.ll_setting_items).setOnClickListener(this);
        $(R.id.btn_setting_copy).setOnClickListener(this);
        $(R.id.tv_setting_profile_modify).setOnClickListener(this);
        $(R.id.tv_setting_account_safety).setOnClickListener(this);
        $(R.id.tv_setting_permision_check).setOnClickListener(this);
        $(R.id.ll_setting_real_name_authentication).setOnClickListener(this);
        $(R.id.ll_setting_balance_way).setOnClickListener(this);
        $(R.id.tv_setting_vip_authentication).setOnClickListener(this);
        $(R.id.tv_setting_black_list).setOnClickListener(this);
        $(R.id.tv_setting_notice).setOnClickListener(this);
        $(R.id.ll_setting_clear_cache).setOnClickListener(this);
        $(R.id.tv_setting_help_and_feedback).setOnClickListener(this);
        $(R.id.tv_setting_provision).setOnClickListener(this);
        $(R.id.tv_setting_logout).setOnClickListener(this);
        $(R.id.tv_setting_about).setOnClickListener(this);
        registerSocketNotify();
    }


    private void logout() {
        DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), getString(R.string.str_login_loginout));
        AccountManager.getInstance().logout(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                //AccountManager.getInstance().deleteOuah(SettingActivity.this);
                DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                IMayCocos.logout();
                IMYScheduler.getInstance().stopSocketService();
                IMYScheduler.getInstance().startSocketService();
                ActivityHelper.getInstance().finishActivity(MainActivity2.class);
                MainActivity2.startActivityForLogout(SettingActivity.this, BaseUserActivity.OPEN_USER_FRAGMENT);
                finish();
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                //LoginActivity.startActivityForLogout(SettingActivity.this);
                IMYScheduler.getInstance().stopSocketService();
                IMYScheduler.getInstance().startSocketService();
                ActivityHelper.getInstance().finishActivity(MainActivity2.class);
                MainActivity2.startActivityForLogout(SettingActivity.this, BaseUserActivity.OPEN_USER_FRAGMENT);
                finish();
            }
        });

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_setting_logout:
                DialogUtil.getNormalDialog(SettingActivity.this, getString(R.string.logout_warning), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        logout();
                        if (!TimeUtil.getToday().equals(PreferenceHelper.getInstance().getSaveDay())){
                            PreferenceHelper.getInstance().saveToday();
                        }
                    }
                }).show();
                break;
            case R.id.btn_setting_copy:
                AppUtil.copy(this, tv_setting_imay_number.getText() + "");
                ToastUtil.show(this, R.string.copy_success_roomid);

                break;
            case R.id.tv_setting_profile_modify:
                ProfileEditActivity.start(this);
                break;
            case R.id.tv_setting_account_safety:
                AccountSecurityActivity.start(this);
                break;
            case R.id.tv_setting_permision_check:
                PermisionCheckActivity.start(this);
                break;
            case R.id.ll_setting_real_name_authentication:
                AuthenticationActivity.startActivity(SettingActivity.this);
                break;
            case R.id.ll_setting_balance_way:
                UserSignActivity.startActivity(SettingActivity.this);
                break;
            case R.id.tv_setting_vip_authentication:
                VIPAuthenticationActivity.start(this);
                break;
            case R.id.tv_setting_black_list:
                BlackListActivity.start(this);
                break;
            case R.id.tv_setting_notice:
                PushSettingActivity.start(this);
                break;
            case R.id.ll_setting_clear_cache:
                try {
                    if ("0KB".equals(tv_setting_cache.getText())) {
                        if (index < toastTexts.length - 1) {
                            index++;
                        }
                        ToastUtil.show(this, toastTexts[index]);
                        return;

                    }
                    DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(),getString(R.string.cache_cleaning));
                    String vedioFile = getExternalFilesDir(Environment.DIRECTORY_MOVIES).getPath();
                    String videoPath = FileHelper.getInstance().getImageFile().getAbsolutePath();
                    APPCacheManager.cleanApplicationData(SettingActivity.this.getApplicationContext(), vedioFile, videoPath);
                    ImagePipeline imagePipeline = Fresco.getImagePipeline();
                    imagePipeline.clearCaches();
                    ICUtils.deleteFile(SettingActivity.this.getApplicationContext());
                    refreshCachSize();



                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            case R.id.tv_setting_help_and_feedback:
                HelpAndFeedbackActivity.start(this);
                break;
            case R.id.tv_setting_provision:
                ProvisionActivity.start(this);
                break;
            case R.id.tv_setting_about:
                AboutIMayActivity.start(this);
                break;

        }
    }

    private void setCacheSizeText() {
        tv_setting_cache.setText(APPCacheManager.getCacheSize(getApplicationContext()));
    }

    private void registerSocketNotify() {
        //监听socket
        mSocketNotify = new IMYTBASObject(false);
        mSocketNotify.stringCommand = EventHelper.EVENT_NAMESTATUS;
        mSocketNotify.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(IMYTBASObject object) {
                ProtoResult protoResult = JSON.parseObject(object.stringData, ProtoResult.class);
                if (protoResult.msg_id == MessageId.userRealNameVerifiedReq) {
                    try {
                        JSONObject jsonObject = new JSONObject(protoResult.content);
                        if (jsonObject.has("realNameStatus") && tv_setting_real_name_authentication != null) {
                            final int realNameStatus = jsonObject.getInt("realNameStatus");
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (realNameStatus == 3) {
                                        tv_setting_real_name_authentication.setText(getResources().getString(R.string.vsign_applysuccess));
                                        tv_setting_real_name_authentication.setTextColor(getResources().getColor(R.color.text_75));
                                    } else {
                                        tv_setting_real_name_authentication.setText(getResources().getString(R.string.not_authentication));
                                    }
                                }
                            });
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        mSocketNotify.addEventListenWithTBASObject();
    }

    @Override
    protected void onDestroy() {
        if (mSocketNotify != null) {
            mSocketNotify.destroy();
        }
        super.onDestroy();

    }

    private void refreshCachSize(){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                tv_setting_cache.setText("0KB");

            }
        },2000);
    }


}
